package com.example.userlogin.service;

import com.example.userlogin.dto.JwtResponse;
import com.example.userlogin.dto.LoginRequest;
import com.example.userlogin.security.JwtUtils;
import com.example.userlogin.security.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * 认证服务
 * 职责：用户登录认证、JWT令牌生成
 */
@Service
public class AuthenticationService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 用户登录认证
     */
    public JwtResponse authenticateUser(LoginRequest loginRequest) {
        try {
            // 执行认证
            Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                    loginRequest.getUsername(),
                    loginRequest.getPassword()
                )
            );

            // 设置安全上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 生成JWT令牌
            String jwt = jwtUtils.generateJwtToken(authentication);

            // 获取用户详情
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();

            // 返回JWT响应
            return new JwtResponse(
                jwt,
                userDetails.getId(),
                userDetails.getUsername(),
                userDetails.getEmail()
            );

        } catch (AuthenticationException e) {
            throw new BadCredentialsException("用户名或密码错误", e);
        }
    }

    /**
     * 验证JWT令牌
     */
    public boolean validateJwtToken(String token) {
        return jwtUtils.validateJwtToken(token);
    }

    /**
     * 从JWT令牌获取用户名
     */
    public String getUsernameFromJwtToken(String token) {
        return jwtUtils.getUserNameFromJwtToken(token);
    }

    /**
     * 获取当前认证用户
     */
    public UserDetailsImpl getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetailsImpl) {
            return (UserDetailsImpl) authentication.getPrincipal();
        }
        return null;
    }

    /**
     * 检查用户是否已认证
     */
    public boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && authentication.isAuthenticated() 
            && !(authentication.getPrincipal() instanceof String);
    }
}